from django.contrib.auth import authenticate, login
from django.shortcuts import render, get_object_or_404
from django.shortcuts import get_list_or_404
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.template.defaulttags import csrf_token
from index.models import Login
from index.models import Question

import numpy as np
from pandas import DataFrame
import vincent
import re
# Create your views here.

# def index (request,some):
#	users = get_object_or_404(Login)
#
#	template = loader.get_template("Pyi/index.html")
#	context = RequestContext(request,{
#			'some' : "QIngluan ",
#		})

#	if request.method == "Get":
#		pass
#	elif request.method == "Post":

#		email = request.POST['email']
#		password = request.POST['pass']

#	return HttpResponse(template.render(context))


def sign(request):

    if (request.method == 'POST'):
        if 'name' in request.POST:
            user_name = request.POST["name"]
        else:
            user_name = False
        if 'email' in request.POST:
            user_email = request.POST["email"]
        else:
            user_email = False

        if 'password' in request.POST:
            user_pass = request.POST['password']
        else:
            user_pass = False

        print user_name, user_pass, user_email

        new_user = User.objects.create_user(user_name, user_email, user_pass)
        new_user.is_staff = True
        new_user.save()

        #HttpResponse("Ok ...")

        return HttpResponseRedirect(reverse('index:home'))

    return render(request, 'Pyi/sign.html')


def login_account(request):

    if request.method == "POST":

        name = request.POST['user']
        password = request.POST['password']

        if request.user.is_authenticated:
            logout(request)

        user_this = authenticate(username=name, password=password)
        if not user_this == None:
            login(request, user_this)

            # context = RequestContext(request,{
            #		'name' : name,
            #	})
            if user_this.is_active:
                #template = loader.get_template('Pyi/menu.html')
                return HttpResponseRedirect(reverse('index:home'))
        else:
            return render(request, 'Pyi/login_failed.html')

    elif request.method == "GET":

        if not request.user.is_active:
            return render(request, 'Pyi/index.html')

        #	return HttpResponseRedirect(reverse('index:home'))
        #	return render(request,'Pyi/home.html',{
        #			'name':request.user.username
        #		})
        else:
            return HttpResponseRedirect(reverse('index:home'))


@login_required(login_url='/')
def home(request):

    if request.method == "POST":
        if 'logout' in request.POST:
            value = request.POST['logout']
            if (value != None):
                logout(request)
                return HttpResponseRedirect(reverse('index:login'))
        elif 'id' in request.POST:
            pk_id = request.POST['id']
            return HttpResponseRedirect(reverse('index:question', args=(pk_id,)))

    else:
        template = loader.get_template('Pyi/home.html')
        name = request.user.username
        try:
            all_question = get_list_or_404(Question)

        except Question.DoesNotExist:
            return render(request, "Pyi/home.html", {
                'name': name,
            })
        else:
            context = RequestContext(request, {
                                     'name': name,
                                     'questions': all_question,
                                     })

            return HttpResponse(template.render(context))


#@login_required(login_url="/")
# def menu(request):

#    template = loader.get_template('Pyi/menu.html')

 #   if (request.method == 'POST'):
  #      if_log = request.POST['logout']
   #     user_name = request.POST['name']

    #    context = RequestContext(request, {
     #       'name': user_name,
      #  })

       # return HttpResponse(template.render(context))

#    if (request.method == "GET"):
 #       user_name = request.user.username

  #      context = RequestContext(request, {
   #         'name': user_name,
    #    })

     #   return HttpResponse(template.render(context))

        # return HttpResponseRedirect(reverse('index:home'))


@login_required(login_url="/")
def question(request, statistic):
    template = loader.get_template("Pyi/Question.html")
    if (request.method == 'GET'):
        user_name = request.user.username
        question = get_object_or_404(Question, pk=statistic)
        answers = question.answer_set.all()
        image = question.image
        return render(request, "Pyi/Question.html", {
            'name'	: user_name,
            'question': question,
            'answers': answers,
            'image'	: image.url,
        })
    else:

        question_this = get_object_or_404(Question, pk=statistic)
        if 'select' in request.POST:
        	pk_id = request.POST['select']
        	answer_get = question_this.answer_set.filter(id=pk_id)[0]
        	if_T = answer_get.if_right()
        	if if_T == "T":
        		question_this.right_select_num += 1
        	question_this.all_select_num += 1

        #### data get area ####
        cat_title =[ i for i in get_list_or_404(Question) ]
        index_title = ['A','B','C','D']
        multi_iter = {'index' : index_title}
        for cat in cat_title:
        	multi_iter[str(cat.pub_time)] = [ i.count for i in   cat.answer_set.all() ] 

        stacked = vincent.StackedArea(multi_iter, iter_idx='index')
        stacked.axis_titles(x='answer', y="people's number")
        stacked.legend(title='rate of right ')
        stacked.colors(brew='Accent')
        stacked.to_json('index/static/json/statistic.json')
        return HttpResponseRedirect(reverse('index:result',args=(statistic,)))
        # answer_select = get_object_or_404(arequest.POST['select']

@login_required(login_url="/")
def result_view(request,q_id):
	if request.method== 'GET':
		question = get_object_or_404(Question,id=q_id)
		answers = question.answer_set.all()
		right_a = None
		for i in answers:
			if i.if_right() == "T":
				right_a = i.number

		user_name = request.user.username
		return render(request,'Pyi/result_page.html',{
			'question' : question,
			'answers'	: answers,
			'name'	: user_name,
			'right'	: right_a,
			})
	else :
		if 'look' in request.POST:
			return HttpResponseRedirect(reverse('index:statistic'))

@login_required(login_url="/")
def statistic_result(request):
	if request.method =='GET':
		pattern  = re.compile(r'')
		return render(request,'Pyi/statistic.html')


@login_required
def test(request):
    return HttpResponseRedirect(reverse('index:menu'))
